package top.rainbowecho.notify.infrastructure.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import top.rainbowecho.common.mq.mo.SmsMeta;
import top.rainbowecho.notify.domain.model.sms.SmsSender;

import java.io.IOException;
import java.util.List;

/**
 * @author rainbow
 * @since 2020/4/8 15:25
 */
@Component
@Slf4j
@PropertySource("classpath:application.yml")
public class SmsListener {
    private SmsSender smsSender;

    @Autowired
    public void setSmsSender(SmsSender smsSender) {
        this.smsSender = smsSender;
    }

    @RabbitListener(queues = "${blog.mq.routes.sms.routing}")
    public void listenRegisterSms(SmsMeta smsMeta, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        log.debug("接受到的短信meta数据为：" + smsMeta);
        List<String> phoneNumbers = smsMeta.getPhoneNumbers();
        String[] phoneNumbersArray = phoneNumbers.toArray(new String[0]);
        this.smsSender.sendRegisterSms(smsMeta.getParams(), phoneNumbersArray);

        channel.basicAck(deliveryTag, false);
    }
}
